/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

/* Written by CimCim */

#include "strReplace.h"

signed long strReplace ( char ** ppch_source, char * pch_str2replace, char * pch_replacingStr )
{
    unsigned short us_it = 0;
    unsigned short us_itTemp = 0;
    unsigned short us_lenStrTemp = 0;
    char * pch_strTemp;

	if ( *ppch_source == NULL || pch_str2replace == NULL || pch_replacingStr == NULL )
	{
		printf ( "a \"NULL\" or empty string has been passed in argument\n" );
		return -1;
	}
    pch_strTemp = ( char * ) malloc ( ( strlen ( *ppch_source ) + 1 ) * sizeof ( char ) );
    if ( pch_strTemp == NULL )
    {
        printf ( "Error : problem when allocating memory... (%m)\n" );
        return -1;
    }
    us_lenStrTemp = strlen ( *ppch_source ) + 1;


    while ( us_it < strlen ( *ppch_source ) )
    {
        if ( strncmp ( &( ( *ppch_source )[us_it] ), pch_str2replace, strlen ( pch_str2replace ) ) == 0 )
        {
            us_lenStrTemp += ( strlen ( pch_replacingStr ) - strlen ( pch_str2replace ) );
            pch_strTemp = ( char * ) realloc ( pch_strTemp, us_lenStrTemp * sizeof ( char ) );
            if ( pch_strTemp == NULL )
            {
                printf ( "Error : problem when allocating memory... (%m)\n" );
                return -1;
            }
            strncpy ( &( pch_strTemp[us_itTemp] ), pch_replacingStr, strlen ( pch_replacingStr ) );
            us_itTemp += strlen ( pch_replacingStr );
            us_it += strlen ( pch_str2replace );
        }
        else
        {
            strncpy ( &( pch_strTemp[us_itTemp] ), &( ( *ppch_source )[us_it] ), 1 );
            ++us_it;
            ++us_itTemp;
        }
    }
    pch_strTemp[us_lenStrTemp - 1] = '\0';
    *ppch_source = ( char * ) realloc ( *ppch_source, ( strlen ( pch_strTemp ) + 1 ) * sizeof ( char ) );
    if ( *ppch_source == NULL )
    {
        printf ( "Error : problem when allocating memory... (%m)\n" );
        return -1;
    }
    strncpy ( *ppch_source, pch_strTemp, ( strlen ( pch_strTemp ) + 1 ) );

    
    free ( pch_strTemp );
    pch_strTemp = NULL;
    
    return 0;
}
